#!/usr/bin/python

from zplot import *
import xml.etree.ElementTree as ET
import pprint
import cStringIO


class Way(object):
    def __init__(self, name, nodes, wayxml):
        """ 'nodes' is a dict of IDs -> x,y tuples. """
        self.nodes = []
        self.name = name
        for child in wayxml:
            if child.tag == 'nd':
                ref = int(child.attrib['ref'])
                node = nodes[ref]
                # Throw away duplicate adjacent nodes.
                if len(self.nodes) == 0 or node != self.nodes[-1]:
                    self.nodes.append(node)


    def toString(self):
      s = cStringIO.StringIO()
      s.write(self.name + ': {\n')
      for n in self.nodes:
        s.write('  (' + str(n[0]) + ', ' + str(n[1]) + '),\n')
      s.write('}')
      return s.getvalue()


    def shouldStitch(self, other):
      if self.name != other.name:
        return False
      # Check whether any endpoints are shared.
      if self.nodes[0] == other.nodes[0]:
        return True
      if self.nodes[0] == other.nodes[-1]:
        return True
      if self.nodes[-1] == other.nodes[0]:
        return True
      if self.nodes[-1] == other.nodes[-1]:
        return True
      return False


class Parse(object):
    def __init__(self, path):
        self.tree = ET.parse(path)
        # key = node ID, val = (x,y)
        self.nodes = {}
        self.ways = []
        self.populate()


    def populate(self):
        root = self.tree.getroot()
        nodes = self.nodes

        for node in root.iter('node'):
            nodeid = int(node.attrib['id'])
            # TODO(bryan): Do the conversion to meters properly.
            x = float(node.attrib['lon'])
            y = float(node.attrib['lat'])
            nodes[nodeid] = (x,y)

        for wayxml in root.iter('way'):
            name = None
            # Filter out stuff that isn't roads.
            road = False
            for tag in wayxml.iter('tag'):
                if tag.attrib['k'] == 'name':
                    name = tag.attrib['v']
                elif tag.attrib['k'] == 'highway':
                    road = True

            if road and name:
                way = Way(name, self.nodes, wayxml)
                self.ways.append(way)

        for way1 in self.ways:
          for way2 in self.ways:
            if way1 is way2:
              continue
            if way1.shouldStitch(way2):
              #print "stitch"
              dummy=1

def main():
    p = Parse('data/madison.xml')
    mv.run()


if __name__ == '__main__':
    main()
